package com.twu.biblioteca;

import com.twu.biblioteca.Model.MovieList;
import com.twu.biblioteca.Model.UserList;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MovieCheckOutService implements Service {
    private String borrower = "LiuJing";
    private MovieList movieList;
    private UserList userList;

    public MovieCheckOutService(MovieList movieList) {
        this.movieList = movieList;
    }

    public MovieCheckOutService(MovieList movieList, UserList userList) {
        this.movieList = movieList;
        this.userList = userList;
    }

    @Override
    public String getServiceDescription() {
        return "Checkout Movie";
    }


    @Override
    public Menu getMenu() {
        return null;
    }

    public void doService() {
        if(userList.getLoginUser()!=null){
        System.out.println("Enter the movie ID:");
        String movieID = getMovieID();
        String result = checkOutMovie(movieID);
        System.out.println(result);
        }
        else{
            LoginService loginService = new LoginService(userList);
            loginService.doService();
        }
    }

    public static String getMovieID() {
        BufferedReader selection = new BufferedReader(new InputStreamReader(System.in));
        try {
            return selection.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "That movie is not available";
    }

    private boolean isMovieCanBeCheckOut(String movieId) {
        if (movieList.getMovieList().containsKey(movieId) && !movieList.getMovieList().get(movieId).isCheckOut()) {
            return true;
        }
        return false;
    }

    public String checkOutMovie(String movieID) {
        String result = "Thank you! Enjoy the movie";
        if (isMovieCanBeCheckOut(movieID)) {
            movieList.updateMovieList(movieID, true, borrower);
        } else {
            result = "That movie is not available";
        }
        return result;
    }
}
